﻿/// <reference path="vswd-ext_2.2.js" />
function VDRWindow() {
    var day = new Date();
    var day = new Date();
    var today = day.getFullYear() + '-' + padLeft((day.getMonth() + 1).toString(), "0", 2) + '-' + padLeft(day.getDate().toString(), "0", 2);
    var yyday = addDays(day, -1);
    var yestoday = yyday.getFullYear() + '-' + padLeft((yyday.getMonth() + 1).toString(), "0", 2) + '-' + padLeft(yyday.getDate().toString(), "0", 2);
    var pagesize = 15; 
    var bynamestore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'Handler/HandlerGetByNameList'
        }),
        reader: new Ext.data.JsonReader({
            fields: ['expression', 'alarmindex','activename','inactivename'],
            root: "data"
        }),
        autoLoad: true
    });

    var inputStatusCombox = new Ext.form.ComboBox({
        typeAhead: true,
        mode: 'local',
        triggerAction: 'all',
        editable: false,
        store: bynamestore,
        displayField: 'expression',
        width: 100,
        valueField: 'alarmindex'
    });
    
    
    var controltypestore = new Ext.data.SimpleStore({
        fields: ['id', 'type'],
        data: [
        ['0', _InputReportResource_Active + '->' + _InputReportResource_Inactive]
        , ['1', _InputReportResource_Inactive + '->' + _InputReportResource_Active]
        ]
    });
    
    //load tracker name
    var trackerstore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'Handler/HandlerSearchTrackerName'
        }),
        reader: new Ext.data.JsonReader({
            fields: [{ name: 'trackname'}],
            root: "data"
        }),
        autoLoad:true
    });

    var trackNameCombo = new Ext.ux.form.CheckboxCombo({
        store: trackerstore,
        mode: 'local',
        displayField: 'trackname',
        width: 130,
        valueField: 'trackname',
        enableKeyEvents: true,
        editable: true
    });

    trackNameCombo.on('keyup', function() {
        trackerstore.filter('trackname', trackNameCombo.getRawValue(), true, false);
        trackNameCombo.bindStore(trackerstore);
    });

    trackNameCombo.on('blur', function() {
        trackerstore.clearFilter();
        trackNameCombo.bindStore(trackerstore);
    });
    
    var driverfields = ["driver_id", "driver_name", "driver_age", "driver_email", "driver_phone", "driver_cellphone", "driver_license_model1", "driver_license_model2", "driver_license_model3", "driver_creator_type", "driver_account", "driver_remarks"];
    var driverstore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: "Handler/HandlerSearchDriver",
            method: "POST"
        }),
        reader: new Ext.data.JsonReader({
            fields: driverfields,
            root: "data",
            totalProperty: "totalCount"
        }),
        autoLoad: true
    });

    var driverCombo = new Ext.ux.form.CheckboxCombo({
        name: 'driver_id',
        hiddenName: 'driver_id',
        typeAhead: true,
        triggerAction: 'all',
        lazyRender: true,
        mode: 'local',
        store: driverstore,
        valueField: 'driver_id',
        displayField: 'driver_name',
        editable: false,
        width: 130,
        hidden: true
    });
    
    var typeCombo = new Ext.form.ComboBox({
        editable:false,
        disableKeyFilter: true,
        typeAhead: false,
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        width: 50,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 0,
            fields: ['index', 'type'],
            data: [[0, _InputReportResource_TrackerName], [1, _DriverResource_Driver]]
        }),
        width: 100,
        valueField: 'index',
        displayField: 'type'
    });
    
    typeCombo.on('select', function(combo, record, index) {
        if (index == 0) {
            trackNameCombo.setVisible(true);
            driverCombo.setVisible(false);
        }
        else {
            trackNameCombo.setVisible(false);
            driverCombo.setVisible(true);
        }
    });

    var fields = ["driver_name", "vehicle_no","tracker_name", "start_time", "end_time", "start_location", "end_location", "journey_distance", "idle_time", "max_speed"];

    var inputstatustore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy(
        {
            url: "Handler/HandlerGetVDRList",
            method: "POST"
        }),
        reader: new Ext.data.JsonReader(
        {
            fields: fields,
            root: "data",
            totalProperty: "totalCount"
        })
    });



    var controlTypeCombo = new Ext.form.ComboBox({
        typeAhead: false,
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        editable: false,
        triggerAction: 'all',
        store: controltypestore,
        displayField: 'type',
        width: 120,
        valueField: 'id'
    });

    function autoColumnName() {
        var alarmid = inputStatusCombox.getValue();
        var activeName = _InputReportResource_Active + _InputReportResource_Time;
        var inactiveName = _InputReportResource_Inactive + _InputReportResource_Time;
        var tmpactive;
        var tmpinactive;
        bynamestore.each(function(record) {
            if (record.get("alarmindex") == alarmid) {
                tmpactive = record.get('activename');
                tmpinactive = record.get('inactivename');
            }
        });
        if (tmpactive != null)
            activeName = tmpactive;
        if (tmpinactive != null)
            inactiveName = tmpinactive;

        if (controlTypeCombo.getValue() == 0) {
            grdInput.getColumnModel().setColumnHeader(2, activeName + _InputReportResource_Time);
            grdInput.getColumnModel().setColumnHeader(3, inactiveName + _InputReportResource_Time);
            grdInput.getColumnModel().setColumnHeader(4, activeName + _InputReportResource_Address);
            grdInput.getColumnModel().setColumnHeader(5, inactiveName + _InputReportResource_Address);

        }
        else {
            grdInput.getColumnModel().setColumnHeader(3, activeName + _InputReportResource_Time);
            grdInput.getColumnModel().setColumnHeader(2, inactiveName + _InputReportResource_Time);
            grdInput.getColumnModel().setColumnHeader(5, activeName + _InputReportResource_Address);
            grdInput.getColumnModel().setColumnHeader(4, inactiveName + _InputReportResource_Address);
        }
        grdInput.show();
    }

    inputStatusCombox.on('select', function() {
        var alarmid = inputStatusCombox.getValue();
        var activeName = _InputReportResource_Active + _InputReportResource_Time;
        var inactiveName = _InputReportResource_Inactive + _InputReportResource_Time;
        var tmpactive;
        var tmpinactive;
        bynamestore.each(function(record) {
            if (record.get("alarmindex") == alarmid) {
                tmpactive = record.get('activename');
                tmpinactive = record.get('inactivename');
            }
        });
        if (tmpactive != null)
            activeName = tmpactive;
        if (tmpinactive != null)
            inactiveName = tmpinactive;
        controltypestore.getAt(0).set("type", activeName + " -> " + inactiveName);
        controltypestore.getAt(1).set("type", inactiveName + " -> " + activeName);
        controlTypeCombo.setValue('0');
        autoColumnName();
    });


    controlTypeCombo.on('select', function() {
        autoColumnName();
    });
    
    var bar = new Ext.PagingToolbar({
        pageSize: pagesize,
        store: inputstatustore,
        displayInfo: true,
        beforePageText: _Alarm_Page,
        refreshTex: _Alarm_Refresh,
        displayMsg: _Alarm_Displaying,
        emptyMsg: _Alarm_Alarm_emptyMsg
    });

    var fromDateEditor = new Ext.form.DateField({
        renderer: Ext.util.Format.dateRenderer('Y-m-d'),
        format: 'Y-m-d',
        value: yestoday
    });


    var fromTimeEditor = new Ext.form.TimeField({
        value:'00:00',
        format: 'H:i',
        width: 70
    });

    var toDateEditor = new Ext.form.DateField({
        renderer: Ext.util.Format.dateRenderer('Y-m-d'),
        format: 'Y-m-d',
        value: today
    });

    var toTimeEditor = new Ext.form.TimeField({
        value:"23:59",
        format: 'H:i',
        width: 70
    });

    var addressCb = new Ext.form.Checkbox({ checked: false });
    
    var tbar = new Ext.Toolbar({
        items: [
            typeCombo, ' ',
            trackNameCombo,
            driverCombo,
            {
                xtype: 'tbseparator', width: 5
            },
            _InputReportResource_Input + ':',
            inputStatusCombox,
            {
                xtype: 'tbseparator', width: 5
            }, _InputReportResource_StatisticalMethods + ':',
            controlTypeCombo,
            {
                xtype: 'tbseparator', width: 5
            },
            _Alarm_FromTime + ':',
            fromDateEditor,
            {
                xtype: 'tbseparator', width: 5
            },
            fromTimeEditor,
            {
                xtype: 'tbseparator', width: 5
            },
            _Alarm_ToTime + ':',
            toDateEditor,
            {
                xtype: 'tbseparator', width: 5
            },
            toTimeEditor,
            _TrackerMain_ARP,
            addressCb,
            {
                tooltip: { text: _TrackerMain_Search, autoHide: true },
                icon: 'images/search16.gif',
                handler: function() {
                    if (controlTypeCombo.getRawValue() != "" || inputStatusCombox.getRawValue() != "") {
                        inputstatustore.load({ params: {
                            fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
                            totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
                            inputID: inputStatusCombox.getValue(),
                            trackName: trackNameCombo.getRawValue(),
                            controlTypeID: controlTypeCombo.getValue(),
                            byName: inputStatusCombox.getRawValue(),
                            start: 0,
                            limit: pagesize,
                            searchType: typeCombo.getValue(),
                            driverIds: driverCombo.getValue()
                        }
                        });
                    }
                    else {
                        Ext.Msg.alert(_Alarm_NoData, _Alarm_NoData);
                    }
                }
            },
            {
                tooltip: { text: _TrackerMain_ExportToExcel, autoHide: true },
                icon: 'images/excel16.gif',
                handler: function() {
                    if (controlTypeCombo.getRawValue() != "" || inputStatusCombox.getRawValue() != "") {
                        if (!Ext.fly('inputreportexcel')) {
                            var frm = document.createElement('form');
                            frm.id = 'vdrexcel';
                            frm.name = id;
                            frm.style.display = 'none';
                            document.body.appendChild(frm);
                        }
                        Ext.Ajax.request({
                            url: 'Handler/HandlerExcel',
                            form: Ext.fly('vdrexcel'),
                            method: 'POST',
                            params: {
                                exceltype: 'vdrexcel',
                                start: 0,
                                fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
                                totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
                                inputID: inputStatusCombox.getValue(),
                                trackName: trackNameCombo.getRawValue(),
                                controlTypeID: controlTypeCombo.getValue(),
                                byName: inputStatusCombox.getRawValue(),
                                timeHeader: controlTypeCombo.getRawValue(),
                                start: 0,
                                limit: 63354,
                                searchType: typeCombo.getValue(),
                                driverIds: driverCombo.getValue()
                            },
                            isUpload: true
                        });
                    }
                    else {
                        Ext.Msg.alert(_Alarm_NoData, _Alarm_NoData);
                    }
                }
            }
        ]
    });

    var trackpointsfields = ["gpstime", "latitude", "longitude", "speed", "direction", "otherinfo", { name: "stopped", type: "bool" }, "stoppedtime"];

    var trackpointreader = new Ext.data.JsonReader({}, trackpointsfields);

    var trackpointstore = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            fields: trackpointsfields,
            root: "data",
            stoptime: "stoptime", //本次搜索停止时间
            end: "end"
        }),
        proxy: new Ext.data.HttpProxy({
            url: 'Handler/HandlerGetTrackPoints',
            timeout: 240000
        })

    });

    var grdInput = new Ext.grid.GridPanel({
        //hidden:true,
        store: inputstatustore,
        
        columns: [
                    { header: _RFIDResource_DriverName, width: 100, sortable: true, menuDisabled: true, dataIndex: 'driver_name' },
                    //{ header: _RFIDResource_VehicleNo, width: 120, sortable: true, menuDisabled: true, dataIndex: 'vehicle_no' },
                    {header: _InputReportResource_TrackerName, width: 120, sortable: true, menuDisabled: true, dataIndex: 'tracker_name' },
                    { header: _RFIDResource_StartTime, width: 140, sortable: true, menuDisabled: true, dataIndex: 'start_time' },
                    { header: _RFIDResource_EndTime, width: 140, sortable: true, menuDisabled: true, dataIndex: 'end_time' },
                    { header: _RFIDResource_StartLocation, width: 140, sortable: true, menuDisabled: true, dataIndex: 'start_location' },
                    { header: _RFIDResource_EndLocation, width: 140, sortable: true, menuDisabled: true, dataIndex: 'end_location' },
                    { header: _RFIDResource_MaxSpeed, width: 100, sortable: true, menuDisabled: true, dataIndex: 'max_speed' },
                    { header: _RFIDResource_JourneyDistance, width: 120, sortable: true, menuDisabled: true, dataIndex: 'journey_distance' },
                    { header: _RFIDResource_IdleTime, width: 100, sortable: true, menuDisabled: true, dataIndex: 'idle_time' }
                 ],
        width: 800,
        height: 400,
        header: false
    });

    grdInput.addListener('rowdblclick', function(grid, rowindex, e) {
        var trackName = inputstatustore.getAt(rowindex).get("name");
        var firsttime = inputstatustore.getAt(rowindex).get("firsttime");
        var lasttime = inputstatustore.getAt(rowindex).get("lasttime");
        trackpointstore.reload({
            params: {
                trackName: trackName,
                fromtime: firsttime,
                totime: lasttime
            },
            callback: function() {
                Ext.MessageBox.hide();
                if (trackpointstore.getCount() > 0) {
                    var rmap;
                    var butStartStop = new Ext.Button({
                        tooltip: { text: _AnimateControl_Stop, autoHide: true },
                        icon: 'images/player_pause.png',
                        handler: function() {
                            if (butStartStop.tooltip.text == _AnimateControl_Stop) {
                                rmap.stopAnimate();
                                butStartStop.setTooltip({ text: _AnimateControl_Continue, autoHide: true });
                                butStartStop.setIcon('images/player_play.png');
                            }
                            else {
                                rmap.startAnimate();
                                butStartStop.setTooltip({ text: _AnimateControl_Stop, autoHide: true });
                                butStartStop.setIcon('images/player_stop.png');
                            }
                        }
                    });
                    var tbar = new Ext.Toolbar({
                        items: [{
                            tooltip: { text: _AnimateControl_ToStart, autoHide: true },
                            icon: 'images/player_start.png',
                            handler: function() {
                                rmap.toStartPoint();
                            }
                        }, {
                            tooltip: { text: _AnimateControl_SlowDown, autoHide: true },
                            icon: 'images/player_rew.png',
                            handler: function() {
                                rmap.slowDownAnimate();
                            }
                        }, butStartStop
                               , {
                                   tooltip: { text: _AnimateControl_SpeedUp, autoHide: true },
                                   icon: 'images/player_fwd.png',
                                   handler: function() {
                                       rmap.speedUpAnimate();
                                   }
                               }, {
                                   tooltip: { text: _AnimateControl_ToEnd, autoHide: true },
                                   icon: 'images/player_end.png',
                                   handler: function() {
                                       rmap.toEndPoint();
                                   }
                               }]
                    });

                    var win = createHistoryMapWindow(_TrackerMain_HistoryLine + '(' + trackNameCombo.getRawValue() + ')');
                    win.tbar = tbar;
                    win.show(); // 显示出来
                    rmap = createMap(win.getMap(), true, null, gmapurl);
                    rmap._parkingTimeCap = _Alarm_ParkingTime;
                    nextwindowx += 20;
                    nextwindowy += 20;
                    rmap.setCenterbyLatLng(0,0);
                    rmap.drawAnimateHistoryLine(trackpointstore, _TrackerMain_GPSTime, _TrackerMain_Speed);
                }
                else {
                    Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
                    Ext.Msg.show({
                        title: _TrackerMain_Title,
                        msg: _Message_NoDataInSelection,
                        buttons: Ext.Msg.OK,
                        animEl: 'elId',
                        icon: Ext.MessageBox.WARNING
                    });
                }
            }
        })
    });

    var inputwindow = new Ext.Window({
        title: _RFIDResource_VehicleDriverRFIDReport,
        layout: 'fit',
        height: 470,
        width: 1200,
        icon: 'images/report_user.png',
        items: grdInput,
        tbar: tbar,
        bbar: bar,
        minimizable: true,
        listeners: {
            'minimize': function() {
                addTaskButtonForWindow(inputwindow);
            },
            'show': function() {
                typeCombo.setValue(0);
                typeCombo.setRawValue(_InputReportResource_TrackerName);
            }
        }
    });

    inputstatustore.on('beforeload', function(store) {
        var t = driverCombo.getRawValue();
        var v = driverCombo.getValue();
        inputstatustore.baseParams = {
            fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
            totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
            inputID: inputStatusCombox.getValue(),
            trackName: trackNameCombo.getRawValue(),
            controlTypeID: controlTypeCombo.getValue(),
            byName: inputStatusCombox.getRawValue(),
            start: 0,
            limit: pagesize,
            searchType: typeCombo.getValue(),
            driverIds: driverCombo.getValue()
        }
    });

    inputstatustore.on("load", function(store) {
        var count = store.getCount();
        if (count >= 1) {
            if (addressCb.getValue() == true) {
//            Ext.MessageBox.show({
//                msg: _Alarm_LoadingAddress,
//                progressText: _CustomerConfigResource_Loading,
//                width: 300,
//                wait: true,
//                waitConfig: { interval: 2000 }
//            });
            
                var i = 0;
                var readAddressInterval1 = window.setInterval(function() {
                    if (i == count) {
                        window.clearInterval(readAddressInterval1);
                        i = 0;
                        var readAddressInterval2 = window.setInterval(function() {
                            if (i == count) {
                                window.clearInterval(readAddressInterval2);
                                Ext.MessageBox.hide();
                                i = 0;
                                return;
                            }
                            var record = store.getAt(i);
                            imap.geoCoder(String(record.data.end_location).split(',')[0], String(record.data.end_location).split(',')[1],
                                           function(address, index) {
                                               if (address == "")
                                                   return;
                                               else
                                                   record.set("end_location", address);
                                               i += index;
                                           });
                        }, 1000);
                        return;
                    }
                    var record = store.getAt(i);
                    imap.geoCoder(String(record.data.start_location).split(',')[0], String(record.data.start_location).split(',')[1],
                               function(address, index) {
                                   if (address == "")
                                       return;
                                   record.set("start_location", address);
                                   i += index;
                               });
                }, 1000);
            }

        }
        else {
            Ext.MessageBox.hide();
            Ext.Msg.alert(_Alarm_NoData, _Alarm_NoData);
        }
        
    });
    inputwindow.show();
};